<?php

namespace App\Http\Requests;

use App\Models\Varietie;
use Illuminate\Validation\Rule;

class VarietieRequest extends RequestPost
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        if (is_null($this->description)) {
            $this->merge(['description' => '']);
        }
        return [
            'exchange_id'       => ['required'],
            'title'             => ['required'],
            'code'              => ['required', function ($attribute, $value, $fail) {
                $info = Varietie::query()->where('code', $value)->where('exchange_id', $this->exchange_id)->first();
                if ($info) {
                    if ($this->id > 0) {
                        if ($info->id != $this->id) {
                            $fail('品种代码不能重复');
                        }
                    } else {
                        if ($info) {
                            $fail('品种代码不能重复');
                        }
                    }
                }
            }],
            'transaction'       => [],
            'closing_quotation' => [],
            'handling_fee'      => [],
            'date_time'         => [],
        ];
    }

    public function messages()
    {
        return [
            'id.required'                => '修改时，id必填',
            'exchange_id.required'       => '交易所ID必填',
            'title.required'             => '名称必填',
            'code.required'              => '品种代码必填',
            'transaction.required'       => '交易价必填',
            'code.unique'                => '品种代码不能重复',
            'closing_quotation.required' => '收盘价必填',
            'handling_fee.required'      => '手续费必填',
            'date_time.required'         => '品种日期必填',
        ];
    }

    public function attributes()
    {
        return [
            'id'                => 'ID',
            'exchange_id'       => '所属交易所ID',
            'title'             => '名称',
            'code'              => '品种代码',
            'transaction'       => '交易价',
            'closing_quotation' => '收盘价',
            'handling_fee'      => '手续费',
            'description'       => '描述',
            'date_time'         => '品种日期',
        ];
    }
}
